home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Shareware Grab Bag
/
Shareware Grab Bag.iso
/
090
/
pctj8505.arc
/
PWRI.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1986-09-14
|
2KB
|
62 lines
FUNCTION RLSCAN(X: REAL; N: INTEGER): REAL;
{This function scans the positive exponent N from right to left
to determine a sequence of multiplications and squarings that
produce X (real) to the power N (integer) in a near-minimum
number of multiplications. It is used as a function in the
function PWRI, listed below. The algorithm is Algorithm A, page
442, Vol. 2, 2nd Ed. of Knuth: "The Art of Computer Programming:
Seminumerical Algorithms", Addison-Wesley, 1981.}
VAR Y,Z: REAL;
O: BOOLEAN;
BIGN: INTEGER;
BEGIN
BIGN := N; Y := 1.0; Z := X;
WHILE BIGN > 0 DO
BEGIN
O := ODD(BIGN);
BIGN := BIGN DIV 2;
IF O THEN
BEGIN
Y := Y*Z;
RLSCAN := Y
END;
Z := Z*Z
END;
END;
FUNCTION PWRI(X: REAL; N: INTEGER): REAL;
{PWRI performs the tests necessary to eliminate the non-
computable cases of finding X (real) to the power N (integer).
It calls upon function RLSCAN to do the actual computation
after it has, for example, replaced a negative exponent by
a positive one (it does a reciprocation after return from
RLSCAN in that case).}
BEGIN
IF (N>0) THEN PWRI := RLSCAN(X,N)
ELSE IF (X<>0.0) AND (N<0) THEN
BEGIN
N := -N;
PWRI := 1.0/RLSCAN(X,N)
END
ELSE IF (N=0) AND (X<>0) THEN PWRI := 1.0
ELSE IF (N=0) AND (X=0) THEN
BEGIN
WRITELN('0 to the 0 power. Halt.');
HALT
END
ELSE IF (N<0) AND (X=0) THEN
BEGIN
WRITELN('Division by zero. Halt.');
HALT
END
END;